<?php

namespace App\Http\Controllers\ZHIHU\Systems;

use DB;
use Response;
use Config;
use Hash;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Ramsey\Uuid\Uuid;
use App\Validate\Zhihu\ZhihuValidator;
use App\Http\Controllers\GBS\Emails\MailSendController;
use Illuminate\Support\Arr;
use Carbon\Carbon;
use App\Eloqumd\Zhihu\ZhihuUser;

class RegisterController extends Controller
{
    // 用户注册
    public function register(Request $request)
    {
        // 数据校验
        $param = $request->all();
        if (true !== $validateRes = ZhihuValidator::register($param)) {
            return Response::json(['code' => 50000, 'message' => $validateRes]);
        }
        // 剔除敏感数据
        $password = Arr::get($param, 'password');
        $param = Arr::except($param, ['password', 'password_confirmation']);

        // redis进行缓存，不入数据库
        $redisKey = Uuid::uuid1()->getHex();
        $emailVerfitTTL = Config::get('api.zhihu_email_verify_expr');
        Redis::setex($redisKey, $emailVerfitTTL, serialize($param));
        Redis::setex($redisKey . '_ps', $emailVerfitTTL, $password);

        // 激活地址组装
        $_timestamp = time();
        $_uuid = urlencode(simple_encrypt($redisKey, 'E', $_timestamp));
        $email_verify_url = Config::get('app.url') . '/api/zhihu/registerEmailVerifyActive?_uuid=' . $_uuid . '&_timestamp=' . $_timestamp;
        $param = Arr::add($param, 'email_verify_url', $email_verify_url);

        // 发送邮件通知
        MailSendController::zhihuRegisterEmailVerifyMail($param);

        return Response::json(['code' => 10000, 'message' => trans('zhihu.The-Register-Success-Please-Email-Verify')]);
    }

    // 邮箱注册校验-输出HTML
    public function registerEmailVerifyActive(Request $request)
    {
        $param = $request->all();

        // 基本参数校验
        $uuid = $param['_uuid'] ?? '';
        $timestamp = $param['_timestamp'] ?? '';
        if (!$uuid || !$timestamp) {
            echo file_get_contents(resource_path() . '/tpl/regsiterError.html');
            exit;
            // return Response::json(['code' => 50000, 'message' => trans('zhihu.Uneffect-Url-Link')]);
        }

        // 非法时间戳
        if (!is_timestamp($timestamp) || $timestamp >= time()) {
            echo file_get_contents(resource_path() . '/tpl/regsiterError.html');
            exit;
            // return Response::json(['code' => 50001, 'message' => trans('zhihu.Uneffect-Url-Link')]);
        }
        // 判断链接是否失效
        $redisKey = simple_encrypt(urldecode($uuid), 'D', $timestamp);
        if(!$redisData = Redis::get($redisKey)) {
            echo file_get_contents(resource_path() . '/tpl/regsiterError.html');
            exit;
            // return Response::json(['code' => 50002, 'message' => trans('zhihu.Email-Verify-Url-Link-Invalid')]);
        }

        // 数据反序列化
        $redisData = unserialize($redisData);

        // 判断用户名及邮箱是否被人抢先注册
        $name = $redisData['name'];
        $email = $redisData['email'];
        if (ZhihuUser::where('name', $name)->count()) {
            echo file_get_contents(resource_path() . '/tpl/regsiterError2.html');
            exit;
            // return Response::json(['code' => 50003, 'message' => trans('zhihu.One-Name-Was-Registered-Rirst')]);
        }
        if (ZhihuUser::where('email', $email)->count()) {
            echo file_get_contents(resource_path() . '/tpl/regsiterError3.html');
            exit;
            // return Response::json(['code' => 50004, 'message' => trans('zhihu.One-Email-Was-Registered-Rirst')]);
        }

        DB::beginTransaction();
        try {
            // 用户正式加入系统用户信息中-不做默认登录-用户自行登录
            $model = new ZhihuUser;
            $model->name = $redisData['name'];
            $model->email = $redisData['email'];
            $solt = Uuid::uuid1()->getHex();
            $model->solt = $solt;
            $model->password = Hash::make(Redis::get($redisKey . '_ps'), ['solt' => $solt]);
            $model->created_at = Carbon::now();
            $model->nickname = rand_nickname();
            $model->save();
            DB::commit();
            echo file_get_contents(resource_path() . '/tpl/regsiterSuccess.html');
            exit;
            // return Response::json(['code' => 10000, 'message' => trans('zhihu.The-Email-Verify-Pass-Please-Sigin')]);
        } catch (\Exception $e) {
            DB::rollBack();
            echo file_get_contents(resource_path() . '/tpl/regsiterError4.html');
            exit;
            // return Response::json(['code' => 50005, 'message' => $e->getMessage()]);
        }
    }

    // 通过邮箱找回密码
    public function retrievePassword(Request $request)
    {
        $param = $request->all();
        if (true !== $validateRes = ZhihuValidator::retrievePassword($param)) {
            return Response::json(['code' => 50000, 'message' => $validateRes]);
        }

        // 加入缓存
        $redisKey = Uuid::uuid1()->getHex();
        $retrievePwdTTL = Config::get('api.zhihu_retrieve_pwd_verify_expr');
        Redis::setex($redisKey, $retrievePwdTTL, serialize($param));

        // 找回密码地址组装
        $_timestamp = time();
        $_uuid = urlencode(simple_encrypt($redisKey, 'E', $_timestamp));
        $retrieve_pwd_url = Config::get('app.url') . '/api/zhihu/retrievePasswordLinkVerifyActiveAndReset';

        $param = Arr::add($param, 'retrieve_pwd_url', $retrieve_pwd_url);
        $param = Arr::add($param, '_uuid', $_uuid);
        $param = Arr::add($param, '_timestamp', $_timestamp);

        // 发送邮件通知
        MailSendController::zhihuRetrievePasswordMail($param);

        return Response::json(['code' => 10000, 'message' => trans('zhihu.The-Retrieve-Password-Please-Email-Operation')]);
    }

    // 找回密码-链接有效校验-重置密码
    public function retrievePasswordLinkVerifyActiveAndReset(Request $request)
    {
        $param = $request->all();
        // 基本参数校验
        $uuid = $param['_uuid'] ?? '';
        $timestamp = $param['_timestamp'] ?? '';
        if (!$uuid || !$timestamp) {
            return Response::json(['code' => 50000, 'message' => trans('zhihu.Uneffect-Url-Link')]);
        }
        // 非法时间戳
        if (!is_timestamp($timestamp) || $timestamp >= time()) {
            return Response::json(['code' => 50000, 'message' => trans('zhihu.Uneffect-Url-Link')]);
        }
        // 判断链接是否失效
        $redisKey = simple_encrypt(urldecode($uuid), 'D', $timestamp);
        if(!$redisData = Redis::get($redisKey)) {
            return Response::json(['code' => 50000, 'message' => trans('zhihu.Verify-Url-Link-Invalid')]);
        }

        // 新密码及确认密码校验-规则
        if (true !== $validateRes = ZhihuValidator::retrievePasswordLinkVerifyActiveAndReset($param)) {
            return Response::json(['code' => 50000, 'message' => $validateRes]);
        }

        // 数据反序列化
        $redisData = unserialize($redisData);

        $email = $redisData['email'];
        // 修改密码
        DB::beginTransaction();
        try {
            $solt = Uuid::uuid1()->getHex();
            $model = ZhihuUser::where('email', $email)->first();
            $model->solt = $solt;
            $model->password = Hash::make($param['password'], ['solt' => $solt]);
            $model->updated_at = Carbon::now();
            $model->save();

            return Response::json(['code' => 10000, 'message' => trans('zhihu.The-Retrieve-Password-Operation-Success')]);
        } catch (\Exception $e) {
            DB::rollBack();
            return Response::json(['code' => 50000, 'message' => $e->getMessage()]);
        }
    }
}
